<template>
  <div class="file-item">
    <template v-if="editable">
      <el-input
        style="margin-right: 10px"
        :model-value="filename"
        :placeholder="placeholder"
        @update:model-value="(val) => emits('update:filename', val)" />
      <el-space>
        <m-svg-icon
          style="cursor: pointer"
          :size="25"
          name="view"
          @click="previewFiles()"
        ></m-svg-icon>
        <MUpload
          ref="uploadRef"
          list-type="text"
          :limit="1"
          :show-file-list="false"
          :model-value="files"
          @change="(files) => fileChangeHandler(files)"
        >
          <m-svg-icon
            style="cursor: pointer; top: 5px"
            :size="25"
            name="upLoad"
          ></m-svg-icon>
        </MUpload> </el-space
    ></template>

    <div v-else @click="previewFiles" class="open-link">
      {{ filename || '--' }}
    </div>
    <MFileList ref="mfileListRef" :fileData="files" />
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'

defineOptions({
  name: 'MFileItem'
})

const emits = defineEmits(['update:filename', 'update:files'])

withDefaults(
  defineProps<{
    placeholder?: string
    editable?: boolean
    filename?: string
    files?: any[]
  }>(),
  {
    editable: true
  }
)

const mfileListRef = ref()

function previewFiles() {
  mfileListRef.value.show()
}

function fileChangeHandler(files) {
  emits('update:filename', files[0]?.name)
  emits('update:files', files)
}
</script>
<style scoped>
.file-item {
  display: flex;
  align-items: center;
}
</style>
